//app.js
App({
  onLaunch: function () {

    
    // 获取用户信息
 
    wx.getSetting({
      success: res => {
        this.login();
        if (res.authSetting['scope.userInfo']) {
          console.log('已授权')
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo

              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res);
              }
            }
          })
        }else{
          console.log('未授权')
        }
      }
    })
  },
  globalData: {
    userInfo: null,
    baseUrl: 'https://jm.shingkang.com:3000/',
    // baseUrl: 'http://localhost:3000/',
    num:'暂未开通宝卡',
    openId:'',
    searchContent:''
  },

  getToken(e) {
    return new Promise((resolve, reject) => {
      // 登录
      var that=this;
      wx.login({
        success: res => {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          console.log(res.code)
          if (res.code) {
            //发送res.code 到后台
            wx.request({
              url: this.globalData.baseUrl + 'product/getToken',
              method: 'POST',
              data: {
                code: res.code
              },
              success(res) {
                
                var openId = JSON.parse(res.data.data).openid;
                wx.setStorageSync('openId', openId);
                var session_key = JSON.parse(res.data.data).session_key;
                that.globalData.openId = openId;
                e.openId = openId;
                e.session_key = session_key;
                console.log(e)
                that.saveInfo(e);
              },
              fail() {
               
              }
            })
          }
        }
      })
    })
  },
  //存储个人信息
  saveInfo(e) {
    this.ajaxPost('product/saveInfo', e, function (res) {
      console.log(res.data.token)
      if (res.code == 1 || res.code == 2) {
        wx.setStorage({
          key: 'token',
          data: res.data.token
        });
      }
    })
  },
  // 获取个人信息
  getUserInfo(e,func){
    console.log('token'+wx.getStorageSync('token'))
    var that=this;
    var openId =wx.getStorageSync('openId');
    this.ajaxPost('product/getUserInfo', { 'openId': openId}, function (res) {
      console.log(res);
      if(res.code==1){    
        that.globalData.userInfo=res.data; 
        console.log(that.globalData);
        that.globalData.num = res.data.ranDomNum
        console.log(res.data.ranDomNum);
        func(res.data);
      }else{
        wx.removeStorage({
          key: 'token',
          success: function(res) {
            console.log('token' + wx.getStorageSync('token'))
          },
        })
      }
    })
  },
  // 数据传输post
  ajaxPost(url, data, func, errfunc) {
    //显示加载中
    this.openLoading('1', '加载中', 'loading', 10000)
    // 声明that=this（作用域原因）
    let that = this
    //  数据请求
    wx.request({
      url: this.globalData.baseUrl + url,
      method: "post",
      data: data,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
      },
      //成功回调函数
      success: function (res) {
        
        // 判断服务器返回码
        if (res.statusCode == 200) {
          // 判断数据返回码
          if (res.data.code == 1 || res.data.code == 2) {
            that.openLoading('2')

            func(res.data)
          } else {
            switch (res.data.code) {
              //未登录，
              case 1007:
                that.loGin()
                that.setData({
                  unLogin: true
                })
                break;
              //验证失败
              case 0:
                that.openToast(res.data.msg, 'none', 2000)
                break;
              default:
                that.openToast('未知错误' + res.data.msg, 'none', 2000)
            }
            if (errfunc) {
              errfunc(res)
            }

          }
        } else {
          that.openLoading('2')
          that.openToast('获取数据失败,错误码' + res.statusCode, 'none', 2000)
        }
      },
      fail: function () {
        console.log("接口调用失败");
      }
    })
  },
  login() {
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    })
  },
  //提示框方法
  openToast: function (title, icon, time) {
    wx.showToast({
      title: title,
      icon: icon,
      duration: time
    });
  },
  //加载中方法
  openLoading: function (type, title, icon, time) {
    switch (type) {
      case '1':
        wx.showLoading({
          title: title,
          icon: icon,
          duration: time

        });
        break;
      case '2':
        wx.hideLoading()
        break;
      default:
        wx.hideLoading()
    }
  }
})